<template>
<view>
  <view class="draw">
    <canvas class="canvas" canvas-id="canvas_sign" @touchstart="touchstart"
					@touchmove="touchmove" @touchend="touchend" disable-scroll="true"></canvas>
  </view>
  <view class="flex_center mt-106">
    <view class="reset">重新绘制</view>
    <view class="pay_btn ml-30">🔒解锁答案</view>
  </view>
</view>
	
</template>

<script>
	export default {
		data() {
			return {
				canvasCtx: '', //绘图图像
				points: [], //路径点集合
				hasSign: false,
				isInit: false,
			}
		},
		mounted(query) {
      this.$nextTick(() => {
        this.canvasCtx = uni.createCanvasContext('canvas_sign', this) //创建绘图对象
        //设置画笔样式
        this.canvasCtx.lineWidth = 6
        // 设置线条的端点样式
        this.canvasCtx.lineCap = 'round'
        // 设置线条的交点样式
        this.canvasCtx.lineJoin = 'round'
        uni.createSelectorQuery().in(this).select('.canvas').boundingClientRect(async (rect) => {
          let canvasw = Math.ceil(rect.width)
          let canvash = Math.ceil(rect.height)
          this.canvasCtx.fillStyle = 'transparent'
          this.canvasCtx.fillRect(0, 0, canvasw, canvash)
          let headerPhtot = await this.getImageInfo('http://content.daylucky.cn/admin/image/m64ff4by7wjss1xb37g6pt5t.png');
          this.canvasCtx.drawImage(headerPhtot.path, 0, 0, canvasw, canvash);
          this.canvasCtx.draw(true)
        }).exec()
       
        
		  },)
		},

		methods: {
			//触摸开始，获取到起点
			touchstart: function(e) {
				if (!this.isInit) {
					this.isInit = true
					this.autographClick(1);
				}
				let startX = e.changedTouches[0].x
				let startY = e.changedTouches[0].y
				let startPoint = {
					X: startX,
					Y: startY
				}
				this.points.push(startPoint)
				//每次触摸开始，开启新的路径
				this.canvasCtx.beginPath()
			},

			//触摸移动，获取到路径点
			touchmove: function(e) {
				let moveX = e.changedTouches[0].x
				let moveY = e.changedTouches[0].y
				let movePoint = {
					X: moveX,
					Y: moveY
				}
				this.points.push(movePoint) //存点
				let len = this.points.length
				if (len >= 2) {
					this.draw() //绘制路径
				}

			},

			// 触摸结束，将未绘制的点清空防止对后续路径产生干扰
			touchend: function() {
				this.points = []
				this.canvasCtx.draw(true)
			},

			/* ***********************************************
			#   绘制笔迹
			#	1.为保证笔迹实时显示，必须在移动的同时绘制笔迹
			#	2.为保证笔迹连续，每次从路径集合中区两个点作为起点（moveTo）和终点(lineTo)
			#	3.将上一次的终点作为下一次绘制的起点（即清除第一个点）
			************************************************ */
			draw: function() {
        console.log(this.canvasCtx, 'this.canvasCtx')
				let point1 = this.points[0]
				let point2 = this.points[1]
				this.points.shift()
				this.canvasCtx.moveTo(point1.X, point1.Y)
				this.canvasCtx.lineTo(point2.X, point2.Y)
				this.canvasCtx.stroke()
				this.canvasCtx.draw(true)
				this.hasSign = true
			},
      getImageInfo(image) {
        return new Promise((req, rej) => {
          uni.getImageInfo({
            src: image,
            success: function (res) {
            req(res);
            },
          });
        })
      },

			// 底部按钮点击操作
			autographClick(type) {
				let that = this
				if (type === 1) {
					//清空画布
					this.hasSign = false
					uni.getSystemInfo({
						success: (res) => {
              this.$nextTick(() => {
                uni.createSelectorQuery().in(this).select('.canvas').boundingClientRect(async (rect) => {
                  let canvasw = Math.ceil(rect.width)
                  let canvash = Math.ceil(rect.height)
                  this.canvasCtx.fillStyle = 'transparent'
                  this.canvasCtx.fillRect(0, 0, canvasw, canvash)
                  let headerPhtot = await this.getImageInfo('http://content.daylucky.cn/admin/image/m64ff4by7wjss1xb37g6pt5t.png');
                  this.canvasCtx.drawImage(headerPhtot.path, 0, 0, canvasw, canvash);
                  this.canvasCtx.draw(true)
                }).exec()
              
              })
						}
					})

				} else {
					if (!this.hasSign) {
						uni.showToast({
							title: '签名不能为空',
							icon: 'none',
							duration: 2000
						})
						return
					}
					uni.getSystemInfo({
						success: function(res) {
							let canvas = uni.createSelectorQuery().select('.canvas')
							canvas.boundingClientRect().exec(function(data) {
								console.log('canvas saveSign:', data[0].width + 'X' + data[0].height)
								let canvasw = Math.ceil(data[0].width)
								let canvash = Math.ceil(data[0].height)
								uni.canvasToTempFilePath({
									destWidth: canvasw,
									destHeight: canvash,
									fileType: 'jpg',
									canvasId: 'canvas_sign',
									success: function(res) {
										console.log('图片导出成功：', res)
										let path = res.tempFilePath

										// 保存图片
										if (type === 2) {
											that.uploadPic(path)
										} else if (type === 3) {
											// 预览图片
											uni.previewImage({
												urls: [path]
											})
										}
									},
									fail: (err) => {
										// http://tmp/2LVQyvzddk2R820a9009dff43323d8e7fc9ef7a8d076.jpg
										console.log('图片导出失败：', err)
									}
								})
							})
						}
					})
				}
			},

			// 图片上传处理
			uploadPic(tempFile) {
				// 1、将本地图片上传到服务器（假装是七牛云服务器）
				// 2、将七牛云返回的链接，上传到我们的服务器平台
				console.log("------:", tempFile);
				uni.showLoading({
					title: '正在上传中...'
				})
				setTimeout(() => {
					uni.showToast({
						title: '假装签名上传成功',
						duration: 2000,
						icon: 'none'
					});
				}, 1000);
			}
		}
	}
</script>

<style lang="scss" scoped>
	.draw {
    width: 588rpx;
    height: 770rpx;
    border-radius: 700rpx;
    // background: url(http://content.daylucky.cn/admin/image/m64ff4by7wjss1xb37g6pt5t.png) no-repeat left top/ 100% 100%;
    -webkit-clip-path: ellipse(54% 54% at 50% 50%);
    overflow: hidden;
    clip-path: ellipse(54% 54% at 50% 50%);
    .canvas {
      width: 100%;
      height: 100%;
    }
  }
  .reset {
    width: 256rpx;
    height: 76rpx;
    font-family: DreamHanSerifCN-W4;
    border-radius: 38rpx;
    border: 2rpx solid #000000;
    font-size: 32rpx;
    line-height: 76rpx;
    color: #000000;
    text-align: center;
  }
  .pay_btn {
    width: 256rpx;
    height: 76rpx;
    background: #000000;
    border-radius: 38rpx;
    font-size: 32rpx;
    color: #FFFFFF;
    line-height: 76rpx;
    text-align: center;
    font-style: normal;
  }

	
</style>
